<template>
  <div class="baseinfo">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <span v-if="selProjectClass == '63'" style = "color: red;">仅申购单一的成型的非生产设备如空调、打饭机等选择该类型，申购生产类设备或需要进场施工维修及装修等需选择工程管理类</span>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
            {{form.projectNo}}
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            ref="projectName"
            label="项目名称"
            prop="projectName"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-input
              v-model="form.projectName"
              @blur="
                () => {
                  $refs.projectName.onFieldBlur()
                }
              "
              placeholder="请输入有效的项目名称" 
              :disabled="form.status>1" 
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item
            label="项目分类"
            prop="projectTypeSubCategory"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <!-- <a-select
              v-model="form.projectTypeSubCategory"
              placeholder="请选择项目分类"
              :options="projectCategoryOptions" :disabled="form.id!=''"  
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select> -->
            <span style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ subName }}</span>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <!-- <a-col :span="8">
          <a-form-model-item
            label="请选择项目细分类"
            ref="manageSubType"
            prop="manageSubType"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.manageSubType"
              placeholder="请选择项目细分类"
              :options="manageSubTypeOptions"
              @change="subChange" 
              :disabled="form.status>1" 
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :span="8">
          <a-form-model-item
            label="项目承担公司"
            ref="factory"
            prop="factory"
            :label-col="{ span: 8 }"
            :wrapper-col="{ span: 15 }"
          >
            <a-select
              v-model="form.factory"
              placeholder="请选择项目承担公司"
              :options="factoryOptions"
              @change="factoryChange"
              show-search
              :filter-option="filterOption"
            >
              <a-icon slot="suffixIcon" type="plus" />
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="implementPlace"
            label="项目实施地点"
            prop="implementPlace"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.implementPlace"
              @blur="
                () => {
                  $refs.implementPlace.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="profitManage"
            prop="profitManage"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
            class="slot-label"
          >
            <span slot="label">受益经营<p>体/人:</p></span>
            <a-textarea
              v-model="form.profitManage"
              @blur="
                () => {
                  $refs.profitManage.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row> -->

      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="implementationDept"
            label="项目实施部门"
            prop="implementationDept"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-textarea
              v-model="form.implementationDept"
              @blur="
                () => {
                  $refs.implementationDept.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="applyReason"
            prop="applyReason"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
            label="立项理由或依据"
          >
            <a-textarea
              v-model="form.applyReason"
              @blur="
                () => {
                  $refs.applyReason.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="filePolicy"
            label="政策文件"
            prop="filePolicy"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-input
              v-model="form.filePolicy"
              @blur="
                () => {
                  $refs.filePolicy.onFieldBlur()
                }
              "
              readOnly
            
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width:calc(100%) "
            >
              <a-tooltip slot="suffix" title="选择政策">
              <a-icon type="plus"  @click="selectPolicy" />
            </a-tooltip>
           </a-input>
          
          </a-form-model-item>
        </a-col>
        
      </a-row> -->
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-model-item
            ref="implementationAfterProfit"
            prop="implementationAfterProfit"
            :label-col="{ span: 3 }"
            :wrapper-col="{ span: 20 }"
            class="slot-label"
          >
            <span slot="label">项目实施后效<p>益及影响说明:</p></span>
            <a-textarea
              v-model="form.implementationAfterProfit"
              @blur="
                () => {
                  $refs.implementationAfterProfit.onFieldBlur()
                }
              "
              :auto-size="{ minRows: 3, maxRows: 5 }"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <table-select-modal
        ref="filePolicySelect"
        :title="filePolicy.title"
        :searchPlaceholder="filePolicy.searchPlaceholder"
        :importColumns="filePolicy.columns"
        :params="filePolicy.params"
        :keywordKey="filePolicy.keywordKey"
        :isAllSelect="false"
        :listUrl="filePolicy.url"
        :emptyAddData="{emptyLink:'/hte-vue/library/file/new/2',emptyText:'点击新建政策吧'}"
        @handlColumnLink="handlPolicyColumnLink"
        @ok="filePolicyHandleOk"
      />
      <five-to-five ref="fiveForm" :projectBuildId="projectBuildId" :change-id="changeId" @addField="addFiveDataToForm"/>
    </a-form-model>
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { DateTimeFormat, strNotNull ,getParamValFromUrl} from '@/utils/common.js'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'

import Vue from 'vue'
export default {
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    TableSelectModal:()=>import('@/components/tools/TableSelectModal'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive')
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    },
    selProjectClass: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    }
  },
  data() {
    return {
      filePolicy:{
        title:'选择政策',
        searchPlaceholder:'请输入关键词进行模糊搜索',
        visible:false,
        url:'/lib/hteLibFile/list/',
        params:{fileType:2,classId:2},
        keywordKey:"allSearch",
          columns: [
          {
            title: '文件编号',
            dataIndex: 'fileNo',
            align: 'center',
            scopedSlots: { customRender: 'link' }
          },
          {
            title: '文件名称',
            dataIndex: 'fileName',
            align: 'left',
          },
        ],
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '',
        projectNo: '',
        projectName: '',
        mainDeptName: '',
        projectType: '',
        projectTypeSubCategory: '',
        manageSubType: '',
        manageSubTypeName: '',
        implementPlace: '',
        profitManage: '',
        implementationDept: '',
        applyReason:'',
        implementationAfterProfit:'',
        factory: '',
        factoryName: '',
        status: 0 ,
        filePolicy:'',
        filePolicyId:'',
      },
      manageSubTypeOptions: [],
      projectCategoryOptions: [],
      factoryOptions: [],
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        implementPlace: [
          { required: true, message: '请输入项目实施地点', trigger: 'blur' },
          { min: 1, max: 150, message: '申请事由不超过150个字符', trigger: 'blur' },
        ],
        profitManage: [
          { required: true, message: '请输入受益经营体/人', trigger: 'blur' },
          { min: 1, max: 200, message: '受益经营体/人不超过200个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        implementationDept: [
          { required: true, message: '请输入项目实施部门', trigger: 'blur' },
          { min: 1, max: 200, message: '项目实施部门不超过200个字符', trigger: 'blur' },
        ],
        applyReason: [
          { required: true, message: '请输入立项理由或依据', trigger: 'blur' },
          { min: 1, max: 500, message: '立项理由或依据不超过500个字符', trigger: 'blur' },
        ],
        implementationAfterProfit:[
          { required: true, message: '请输入项目实施后效益及影响说明', trigger: 'blur' },
          { min: 1, max: 500, message: '项目实施后效益及影响说明不超过500个字符', trigger: 'blur' },
        ]
        // ,
        // filePolicy: [
        //   { required: true, message: '若无法选中相关政策文件的，请先到智库-政策库新建文档', trigger: 'blur' },
        // ],
      },
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      loadFinish: false
    }
  },
  computed: {},
  methods: {
    
    addFiveDataToForm(val,valRef) {
      this.$set(this.form, valRef, val)
    },
    async doSubmit() {
      if(!this.loadFinish){
        layer.message.warning('请等待页面加载完毕')
        return {}  
      }
      var validR=false;
      try{
        validR = await this.$refs.ruleForm.validate();
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      }catch(e){
        validR = false;
      }
      console.log('validR',validR);
      this.form.validResult = validR;
      let res=await this.doSave();
        this.projectBuildId=res;
      return {valid:validR,id:res};
    },
    async doSave(dosubmit) {
      let flag=null;
      var vm = this
      this.form.changeId=this.changeId;
      await postActionAsync(this.url.save, this.form)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id;
            vm.form.projectNo = res.result.projectNo;
            this.$message.success('保存成功')
            return flag=res.result.id;
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
        return flag;
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId,changeId:this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                this.initSubName()
                this.loadFinish = true
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      }else{
        this.loadFinish=true
      }
    },
    factoryChange(value,option) {
      this.form.factoryName = option.componentOptions.children[0].text;
    },
    subChange(value,option) {
      this.form.manageSubTypeName = option.componentOptions.children[0].text;
    },
    initManageSubTypeOptions() {
      var vm = this
      var typeText = '管理项目细分标签'
      if (this.form.projectType === 'MA') {
        typeText = 'MA管理项目细分标签'
      }
      getAction(this.url.codeInfoList, { type: typeText, isdel: 0,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.manageSubTypeOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询管理项目细分标签失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询管理项目细分标签失败:' + res.message)
        })
    },
    //初始化项目子类
    initProjectCategoryOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0, parentid: vm.form.projectClass,pageSize:-1 })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.projectCategoryOptions.push({ value: item.code, label: item.name })
              })

              if (vm.projectCategoryOptions.length === 1) {
                vm.form.projectTypeSubCategory = vm.projectCategoryOptions[0].value
              }
            }
          } else {
            this.$message.warning('查询项目子类失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目子类失败:' + res.message)
        })
    },
    initFactoryOptionsOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目需求公司', isdel: 0,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.factoryOptions.push({ value: item.code, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询项目需求公司失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询项目需求公司签失败:' + res.message)
        })
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    initSubName () {
      var vm = this
      getAction(this.url.codeInfoList, { type: '项目子类', isdel: 0,parentid:60,parentid:vm.form.projectClass,code:vm.form.projectType,pageSize:-1})
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
    selectPolicy(){
      this.$refs.filePolicySelect.open()
     
    },
    filePolicyHandleOk(record){
      if(record.length > 0){
        var file = record[0]
        var filePolicy = file.fileNo + file.fileName 
        this.form.filePolicy =filePolicy
        this.form.filePolicyId = file.id
        this.$refs.filePolicySelect.close()
      }
       
    },
    handlPolicyColumnLink(file){
      let urlJump = this.$router.resolve({ path: `/library/file/view/2/${file.id}/${file.version}` })
      window.open(urlJump.href, '_blank')
    }
  },
  mounted() {
    if (this.projectBuildId == null || this.projectBuildId == '') {
      this.form.projectType = this.selProjectType
      this.form.projectTypeSubCategory = this.selProjectType
      this.form.projectClass = this.selProjectClass
      this.form.createUserName = Vue.ls.get(USER_INFO).realname
      this.form.createDate = DateTimeFormat(new Date())
      this.initSubName()
      let filePolicy = getParamValFromUrl('filePolicy')
      if(!!filePolicy){
        this.form.filePolicy = filePolicy
      }
    }
    this.initProjectCategoryOptions()
    //this.initManageSubTypeOptions()
    this.initFactoryOptionsOptions()
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
</style>